<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" prop="place">
        <el-input
          v-model="queryParams.place"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['content:show:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['content:show:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['content:show:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="showList"
      @selection-change="handleSelectionChange" border
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" :index="createIndex"/>
      <el-table-column label="轮播图" align="center" prop="pcUrl">
       <!-- 图片的显示 -->
                 <template   slot-scope="scope">            
                    <img :src="scope.row.pcUrl"  min-width="70px" height="70px" 
                           @click="previewPic(scope.row.pcUrl)" />
                 </template>   
      </el-table-column>
      <el-table-column label="链接地址" align="center" prop="linkUrl" />
      <el-table-column label="序号" align="center" prop="serial" />
      <el-table-column label="是否推荐" align="center" prop="recommend">
          <template slot-scope="scope">
              <el-switch
                v-model="scope.row.recommend"
                 active-color="#13ce66"
                 inactive-color="#ff4949"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['content:show:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['content:show:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 图片预览   放在表格外面，这是个弹出狂-->
      <el-dialog :visible.sync="dialogVisible" :modal="false" title="图片预览" width="50%">
        <img :src="previewpic" alt=""  width="100%" />
        <span slot="footer" class="dialog-footer">
          </span>
       </el-dialog>
  <!-- 图片预览 -->

    <!-- 添加或修改轮播图对话框 -->
    
      <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="首页推荐" prop="recommend">
          <el-select
            v-model="form.recommend"
            placeholder="请选择"
            @change="selectStatus"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="轮播图" prop="pcUrl">
          <div
          class="avatar-uploader"
          >
          <img v-if="this.form.pcUrl" :src="this.form.pcUrl" class="avatar" @click="uploaImage(imageUrl)">
          <i v-else class="el-icon-plus avatar-uploader-icon" @click="uploaImage(imageUrl)"></i>
        </div>

        
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input
            v-model="form.linkUrl"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="推荐序号" prop="serial">
          <el-input v-model="form.serial" placeholder="请输入推荐序号" />
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="title" :visible.sync="imageOpen" width="50%" append-to-body @opened="modalOpened"  @close="closeDialog">
      <el-row :gutter="50">
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <vue-cropper
            ref="cropper"
            :img="imageOptions.img"
            :info="true"
            :autoCrop="imageOptions.autoCrop"
            :autoCropWidth="imageOptions.autoCropWidth"
            :autoCropHeight="imageOptions.autoCropHeight"
            :fixedBox="imageOptions.fixedBox"
            @realTime="realTime"
            v-if="imageOpen"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height: '350px'}">
          <div class="previewUrl">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :md="2">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :md="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :md="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :md="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {
  listShow,
  getShow,
  delShow,
  addShow,
  updateShow,
  uploadAvatar
} from "@/api/content/show";
import { VueCropper } from "vue-cropper";
export default {
  name: "Show",
  components: { VueCropper },
  data() {
    return {
      show: {},
      dialogfull: true,
      // 遮罩层
      loading: true,
      dialogVisible: false,
      previewpic: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 轮播图表格数据
      showList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        asId: null,
        pcUrl: null,
        relatedId: null,
        linkUrl: null,
        recommend: null,
        serial: null,
        type: null,
        place: null,
        status: null,
      },
      imageOpen:false,
      imageUrl:'',
      imageOptions: {
        img:"", //裁剪图片的地址
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 200, // 默认生成截图框宽度
        autoCropHeight: 200, // 默认生成截图框高度
        fixedBox: false // 固定截图框大小 不允许改变
      },
      previews: {},

      options: [
        {
          value: 0,
          label: "不推荐",
        },
        {
          value: 1,
          label: "推荐",
        },
      ],
      value: "1",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        asId: [{ required: true, message: "协会id不能为空", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    
     // 打开弹出层结束时的回调
     modalOpened() {
      this.imageOpen = true;
    },
     // 关闭窗口
     closeDialog() {
      this.imageOpen = false;
    },
     // 覆盖默认的上传行为
     requestUpload() {
    },
        // 上传预处理
        beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.imageOptions.img = reader.result;
        };
      }
    },
     // 图片缩放
     changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
     // 上传图片
   uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData();
        formData.append("avatarfile", data);
        uploadAvatar(formData).then(res => {
          console.info(res);
          this.form.pcUrl=res.imgUrl;
          this.$modal.msgSuccess("上传成功");
          this.imageOpen = false;
        });
      });
    },
     // 实时预览
     realTime(data) {
      this.previews = data;
    },
    //创建序号索引
    createIndex(index){
      return (this.queryParams.pageNum - 1) *this.queryParams.pageSize + index + 1;
    },
    uploaImage(val){
      console.info(val);
        this.imageOpen=true;
        this.title="裁剪轮播图"
    },
    selectStatus() {
      console.log(this.options);
    },
    /** 查询轮播图列表 */
    getList() {
      this.loading = true;
      listShow(this.queryParams).then((response) => {
        this.showList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //图片放大
    previewPic(url) {
      this.previewpic = url;
      this.dialogVisible = true;
        },
     handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.id + '"公告吗？').then(function() {
        return changeNoticeStatus(row.id, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "2" : "0";
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        asId: null,
        pcUrl: null,
        relatedId: null,
        linkUrl: null,
        recommend: null,
        serial: null,
        type: null,
        place: null,
        createTime: null,
        updateTime: null,
        status: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加轮播图";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getShow(id).then((response) => {
        console.info(response);
        this.form = response.data;
        this.imageUrl=response.data.pcUrl;
        this.user = response.data;
        this.open = true;
        this.title = "修改轮播图";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateShow(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addShow(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除轮播图编号为"' + ids + '"的数据项？')
        .then(function () {
          return delShow(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/show/export",
        {
          ...this.queryParams,
        },
        `show_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border-width: thin;
    border-style: solid;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .user-info-head {
  position: relative;
  display: inline-block;
  height: 120px;
  margin-right: 600px;
}

.user-info-head:hover:after {
  content: '+';
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 24px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 110px;

}
.previewUrl {
	position: absolute;
	top: 50%;
	transform: translate(50%, -50%);
	width: 200px;
	height: 200px;
	box-shadow: 0 0 4px #ccc;
	overflow: hidden;
} 
</style>